package pri.jz.keeper.ui.login

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import pri.jz.keeper.R
import pri.jz.keeper.repository.UserRepository
import pri.jz.keeper.repository.LoginRepository
import pri.jz.keeper.ui.base.BaseViewModel
import pri.jz.keeper.webservice.WebService
import pri.jz.keeper.webservice.retrofit.LoginService
import pri.jz.keeper.webservice.retrofit.UserService

/**
 *Author by: JZ
 *Email: 2451756617@qq.com
 *PS:
 */
class LoginViewModel(private val application: Application) : BaseViewModel(application) {
    private val _loginUiState = MutableStateFlow(LoginUiState())
    val loginUiState = _loginUiState.asStateFlow()

    private val _loginState = MutableStateFlow<LoginState>(LoginState.DEFAULT) //界面切换状态
    val loginState = _loginState.asStateFlow()

    var numberText by mutableStateOf("")
        private set
    var passwordText by mutableStateOf("")
        private set

    private val loginRepository by lazy {
        LoginRepository()
    }
    private val userRepository by lazy {
        UserRepository.getIns()
    }

    /**
     * 是否跳过登录
     * @return
     */
    private fun isTest(): Boolean {
        return true
    }

    fun numberTextChange(newNumberText: String) {
        numberText = newNumberText
        val b = newNumberText.length != 11
        numberState(
            b,if (b) "手机号格式不正确" else "手机号"
        )
    }
    fun passwordTextChange(newPasswordText: String) {
        passwordText = newPasswordText
        val b = newPasswordText.length !in 6 .. 20
        passwordState(
            b,if (b) "密码格式不正确" else "密码"
        )
    }

    private fun numberState(isError: Boolean,label: String) {
        _loginUiState.update {
            it.copy(isNumberError = isError, numberLabel = label)
        }
    }
    private fun passwordState(isError: Boolean,label: String) {
        _loginUiState.update {
            it.copy(isPasswordError = isError, passwordLabel = label)
        }
    }

    /**
     * 登录事件
     */
    fun login() {
        if (isTest()) { //管理员账号直接通过
            setState(LoginState.SUCCESS(-1))
        } else if (numberText.isBlank()) {
            numberState(true,"用户名不能为空")
        } else if (passwordText.isBlank()) {
            passwordState(true,"密码不能为空")
        } else {
            loginUiState.value.apply {
                if (!(isNumberError || isPasswordError)) {
                    checkUser()
                }
            }
        }
    }



    private fun loginTest() {
        viewModelScope.launch(Dispatchers.IO) {
            val l = WebService.retrofitClient.create(UserService::class.java)
            Log.d(TAG, "loginTest: ${l.getUser("1")}")

        }
    }

    /**
     * 检查登录信息是否正确
     */
    private fun checkUser() {
        requestLoadLaunch {
            loginRepository.userLogin(
                numberText,
                passwordText,
                onUserNonExist = {
                    showTip("用户不存在")
                    numberState(true,"用户不存在")
                },
                onPasswordWrong = {
                    passwordState(true,"密码不正确")
                },
                onLoginSuccess = { id ->
                    loginSuccess(id)
                }
            )
        }
    }

    /**
     * 登录成功
     */
    private fun loginSuccess(id: Int) {
        application.getSharedPreferences(
            application.getString(R.string.shard_table_name_user), Context.MODE_PRIVATE
        ).edit().putInt(application.getString(R.string.shard_table_user_id),id).apply()
        viewModelScope.launch {
            userRepository.userId = id
            setState(LoginState.SUCCESS(id))
        }
    }

    /**
     * 注册
     */
    fun register() {
        setState(LoginState.REGISTER)
    }


    private fun setUiState(loginState: LoginUiState) {
        if (_loginUiState.value != loginState) {
            _loginUiState.value = loginState
        }
    }


    private fun setState(state: LoginState) {
        if (state != _loginState.value) {
            _loginState.value = state
            _loginState.value = LoginState.DEFAULT
        }
    }


}
